<template>
  <a-radio-group
    :value="value"
    @update:value="(v) => handleUpdate(v)"
    style="width: 100%"
  >
    <a-row
      type="flex"
      style="margin: 8px"
      v-for="(item, index) in options"
      :key="item.key"
    >
      <a-col>
        <a-radio :value="item.key">
          <span align="center">选项{{ index + 1 }}</span>
        </a-radio>
      </a-col>
      <a-col :flex="1">
        <a-input :value="item.optionContent" style="flex: 1" disabled></a-input>
      </a-col>
    </a-row>
  </a-radio-group>
</template>
<script lang="ts" setup>
import { uuid } from "@/utils";
import { onMounted, watch } from "vue";
import type { Option } from "@/api/answer/base-data/exercises/typing";

interface Props {
  /**答案 */
  value: string;
  /**选项列表 */
  options: Option[];
}
const props = defineProps<Props>();
const emit = defineEmits(["update:value", "update:options"]);

/**新增行 */
const initRow = (optionContent: string) => {
  return { optionContent, optionId: null, key: uuid() };
};

/**默认选项 */
const defaultOptions = () => {
  return new Array(2).fill(null).map((_m, i) => initRow(i ? "错" : "对"));
};

/**更新答案 */
const handleUpdate = (value: string) => {
  emit("update:value", value);
};

watch(
  () => props.options,
  (options) => {
    for (const item of options) {
      item.key = uuid();
    }
  },
  { immediate: true }
);
watch(
  () => props.value,
  (value) => {
    const item = props.options.find((f) => f.optionId == value);
    if (item) {
      emit("update:value", item.key);
    }
  },
  { immediate: true }
);

onMounted(() => {
  if (!props.options || props.options.length != 2) {
    emit("update:options", defaultOptions());
  }
});
</script>
